﻿using FastBuild.TimeJob;
using SqlSugar;
using Wechat_PublicNumber.Common;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model;
using Wechat_PublicNumber.Model.Input.PublicNumberPushTemplate;
using Wechat_PublicNumber.Repository;

namespace Wechat_PublicNumber.Jobs
{
    [SkipWhileExecuting]
    public class SupplementWeekdayRemindJob : DataAccess, IJob
    {

        #region DI

        [Autowired]
        private WxHttpInvoke _wxHttpInvoke;

        [Autowired]
        private WxTemplateRepository _templateRepository;

        #endregion

        public async Task Execute()
        {
            try
            {
                _logger.Info("SupplementWeekdayRemindJob Begin", "SupplementWeekdayRemindJob");

                var today = DateTime.Now.Date;
                var tomorrow = DateTime.Now.Date.AddDays(1);

                //假期补班数据
                var bubanData = await WXDb.Queryable<Holiday, HolidayTime>((h, ht) => new object[]
                 {
                    JoinType.Left,h.ID==ht.HolidayID
                 })
                .Where((h, ht) => ht.Type == HolidayTypeEnum.SupplementWeekday && (ht.Time == today || ht.Time == tomorrow))
                .Select((h, ht) => new
                {
                    h.Name,
                    ht.Time
                })
                .ToListAsync();

                if (bubanData.GroupBy(h => h.Name).Count() > 1)
                    bubanData.RemoveAll(s => s.Time == today);

                //j 是，m 是
                //j 不是，m 是   发送
                //j 是，m 不是
                if (bubanData.Count == 1 && bubanData.Any(s => s.Time == tomorrow))
                {
                    var openIdList = await _wxHttpInvoke.UserOpenIdList();

                    var pushData = await _templateRepository.GetTemplateData(WeChatTemplateEnum.SupplementWeekday, openIdList.data.openid, new SupplementWeekdayTemplateInput() { Holiday = bubanData.First().Name });

                    if (pushData is not null) await _wxHttpInvoke.PushTemplate(pushData);

                    _logger.Info($"SupplementWeekdayRemindJob End，Push Count:{openIdList.data.openid.Count}条", "SupplementWeekdayRemindJob");
                }
                else
                    _logger.Info($"SupplementWeekdayRemindJob End，No holiday supplementweekday", "SupplementWeekdayRemindJob");

                GC.Collect();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "SupplementWeekdayRemindJob Error", "SupplementWeekdayRemindJob");
            }
        }
    }
}
